package ks.client.controllers.requests;

import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import ks.client.UserContext;
import ks.client.lobby.Lobby;
import ks.framework.common.Message;
import ks.framework.interfaces.IProcessMessage;
import ks.managers.user.User;
import ks.managers.user.UserManager;

/**
 * The controller for the users request.
 * 
 * @author Christopher Page
 */
public class UsersController implements IProcessMessage {

	/** In case we need to process something. */
	Lobby lobby;
	
	/** Construct controller with lobby. */
	public UsersController(Lobby lobby) {
		this.lobby = lobby;
	}

	/**
	 * Client has received users message. Process it.
     * 
	 * @param m
	 * @return
	 */
	public boolean process(Message m) {
		// Get context
		UserContext context = lobby.getUserContext();
		
		// get UserManager instance
		UserManager um = context.getUserManager();
		
		// extract information from the message
		NodeList playersList = m.contents().getChildNodes();
		
		User tmpUser;
		Node tmpPlayer;
		NamedNodeMap tmpNNM;
		Node tmpName;
		Node tmpRating;
		Node tmpIcon;
		Node tmpStatus;
		
		um.removeAllUsers();
		
		for (int i=0; i<playersList.getLength(); i++) {
			tmpPlayer = playersList.item(i);
			
			if (tmpPlayer == null)
				continue;
			
			tmpNNM = tmpPlayer.getAttributes();
			tmpName = tmpNNM.getNamedItem("name");
			tmpRating = tmpNNM.getNamedItem("rating");
			tmpIcon = tmpNNM.getNamedItem("icon");
			tmpStatus = tmpNNM.getNamedItem("online");
			
			if (tmpName == null)
				continue;
			else
				tmpUser = new User(tmpName.getNodeValue(), "");
			
			if (tmpRating != null)
				tmpUser.setRating(Integer.parseInt(tmpRating.getNodeValue()));
			
			if (tmpIcon != null)
				tmpUser.setIconName(tmpIcon.getNodeValue());
			
			um.addUser(tmpUser);
		}
		
		return true;
	}
}
